package cn.iocoder.yudao.module.policy.controller.admin;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.policy.vo.ai.VolcArkResponse;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.security.PermitAll;

@Tag(name = "APP - AI")
@RestController
@RequestMapping("/app/ai")
@Validated
public class AIController {

    // 硬编码 API Key 和配置（实际项目建议用配置中心管理）
    private static final String API_KEY = "0aa6d698-676d-48bd-982c-58b140992bfb";
    private static final String MODEL_ID = "ep-20250524234845-b5hvt";
    private static final String API_URL = "https://ark.cn-beijing.volces.com/api/v3/chat/completions";
    private static final String CONTENT_TYPE = "application/json; charset=utf-8";
    // 使用Spring注入的ObjectMapper或新建实例
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final RestTemplate restTemplate;

    public AIController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("/replacement")
    @Operation(summary = "帮写")
    @PermitAll
    public CommonResult<String> replacement(String message) {
        String s = this.chatWithVolcArk(message);
        System.err.println(s);
        VolcArkResponse volcArkResponse = JSONObject.parseObject(s, VolcArkResponse.class);
        //        return CommonResult.success("AI生成简历是一个利用人工智能技术自动创建或优化求职者简历的智能化功能。该功能通过分析用户输入的基本信息、工作经历、教育背景等数据，自动生成专业、规范且有针对性的求职简历。");
        return CommonResult.success(volcArkResponse.getChoices().get(0).getMessage().getContent());
    }


    /**
     * 调用火山方舟 AI 聊天接口
     */
    public String chatWithVolcArk(String userMessage) {
        try {
            // 构建请求体
            ObjectNode requestBody = objectMapper.createObjectNode();
            requestBody.put("model", MODEL_ID);

            ObjectNode message = objectMapper.createObjectNode();
            message.put("role", "user");
            message.put("content", userMessage);

            requestBody.putArray("messages").add(message);

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(CONTENT_TYPE));
            headers.set("Authorization", "Bearer " + API_KEY);

            // 发送请求
            HttpEntity<String> request = new HttpEntity<>(objectMapper.writeValueAsString(requestBody), headers);

            ResponseEntity<String> response = restTemplate.exchange(API_URL, HttpMethod.POST, request, String.class);

            return response.getBody();
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON处理失败", e);
        } catch (Exception e) {
            throw new RuntimeException("API调用失败", e);
        }
    }

}
